package com.Bigbluebook.http;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class PermissionUtils {

    private static final int REQUEST_CODE = 100; // 用于请求权限的请求码

    public static void requestInternetPermission(final Activity activity) {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，则进行请求
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.INTERNET}, REQUEST_CODE);
        } else {
            // 已经获得权限，可以进行网络操作
            onPermissionGranted(activity);
        }
    }

    public static void onPermissionGranted(Activity activity) {
        // 执行网络操作
        Toast.makeText(activity, "网络权限已授权，可以进行网络操作", Toast.LENGTH_SHORT).show();
    }

    public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults, final Activity activity) {
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予
                onPermissionGranted(activity);
            } else {
                // 权限被拒绝
                Toast.makeText(activity, "需要网络权限来执行此操作", Toast.LENGTH_SHORT).show();
            }
        }
    }
}